/*
 * @Author: zu1662
 * @LastEditor: zu1662
 * @Date: 2019-12-16 16:26:12
 * @LastEditTime: 2021-09-09 09:56:15
 * @Description: axios request封装
 */
import Vue from 'vue'
import axios from 'axios'
import store from '@/store'
import router from '@/router/index'
import { Notification, MessageBox } from 'element-ui'
import { ACCESS_TOKEN, LOCKER_PSW, LOCKER_REDIRECT, SET_LOCKER, USERID } from '@/config/variableInit'

// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL, // api base_url
  timeout: 30000 // 请求超时时间
})
// console.log(process.env.NODE_ENV)
let cancelList = []
// error handle
const err = (error) => {
  // if (!error.response) {
  //   Notification.error({
  //     title: '网络错误',
  //     message: '请检查网络连接，然后重试。'
  //   })
  //   return false
  // }
  if (error.response) {
    const data = error.response.data
    const token = Vue.ls.get(ACCESS_TOKEN)
    if (error.response.status === 403) {
      Notification.error({
        title: 'Forbidden',
        message: data.message
      })
    } else if (error.response.status === 401) {
      if (error.response.data.messageCode === 'ADAPTER-ACCOUNT2B-MGMT-SIGN-IN-001') {
        Notification.error({
          title: '提示',
          message: '登录失败，用户名或者密码不正确'
        })
      } else {
        const urlToken = getQueryVariable('token')
        if (urlToken && urlToken !== '') {
          Vue.ls.remove(ACCESS_TOKEN)
          Vue.ls.remove(SET_LOCKER)
          Vue.ls.remove(LOCKER_PSW)
          Vue.ls.remove(LOCKER_REDIRECT)
          router.replace({ name: 'login' })
        } else {
          MessageBox.alert('您的会话已过期，请重新登陆', '', {
            confirmButtonText: '登陆',
            showClose: false
          }).then(() => {
            if (token) {
              store.dispatch('Logout').then(() => {
                setTimeout(() => {
                  window.location.reload()
                }, 500)
              })
            }
          })
        }
      }
    } else if (error.response.status >= 500) {
      MessageBox.alert('服务异常,请联系管理人员', '', {
        confirmButtonText: '确认',
        showClose: false
      })
    }
    // 取消请求
    cancelList.forEach((cancel) => {
      cancel('Canceled')
    })
    cancelList = []
  }
  return Promise.reject(error.response.data)
}

// request interceptor
service.interceptors.request.use(config => {
  // 设置cancelToken对象
  config.cancelToken = new axios.CancelToken(function (c) {
    cancelList.push(c)
  })
  const token = Vue.ls.get(ACCESS_TOKEN)
  const userId = Vue.ls.get(USERID)
  if (token) {
    config.headers[ACCESS_TOKEN] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  if (!config.headers['Content-Type']) {
    config.headers['Content-Type'] = 'application/json;charset=UTF-8'
  }
  if (!config.headers.state) {
    config.headers.state = 'state'
  }
  if (!config.headers.userId) {
    config.headers.userId = userId
  }
  return config
}, err)

// response interceptor
service.interceptors.response.use((response) => {
  const requestResponseType = response.config.responseType
  if (requestResponseType) { // 判断是文件下载类型
    if (response.status === 200) {
      return response
    } else {
      MessageBox({
        message: 'System Error',
        type: 'error',
        duration: 5 * 1000,
        customClass: 'message-index'
      })
    }
    return false
  }
  return response.data
}, err)

function getQueryVariable (variable) {
  const query = window.location.search.substring(1)
  const vars = query.split('&')
  for (let i = 0; i < vars.length; i++) {
    var pair = vars[i].split('=')
    if (pair[0] === variable) { return pair[1] }
  }
  return (false)
}

const AxiosPlugin = {}
AxiosPlugin.install = (Vue) => {
  Vue.prototype.$http = service
}

export {
  service,
  AxiosPlugin
}
